import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_ble_demo/model/device_model.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_comm_base_framework/core/CommBasePage.dart';
import 'package:flutter_comm_base_framework/core/utils/time_utils.dart';
import 'package:flutter_comm_base_framework/core/view/my_appbar.dart';
import 'package:flutter_comm_base_framework/core/widgets/custom_button.dart';
import 'package:flutter_comm_base_framework/core/widgets/custom_text.dart';

class BleSendReceivePage extends CommBasePage {
  @override
  CommBaseState getPageState() {
    return BleSendReceivePageState();
  }
}

class BleSendReceivePageState extends CommBaseState<BleSendReceivePage> {
  BluetoothDevice deviceModel;
  TextEditingController txController = new TextEditingController();
  List<String> revMsgLst = [];

  BluetoothCharacteristic bluetoothCharacteristic;

  @override
  void initBaseParams() {
    // TODO: implement initBaseParams
  }

  @override
  void initPageData() {
    deviceModel = ModalRoute.of(context).settings.arguments;
    setState(() {
      txController.text = "A5 5A 04";
    });
  }

  @override
  Widget getViewsWidget() {
    return Scaffold(
      appBar: MyAppBar(
        title: Text(
          deviceModel != null ? "${deviceModel.id}" : "",
          style: TextStyle(fontSize: 18, color: Colors.white),
        ),
      ),
      body: Column(
        children: [
          Row(
            children: [
              Expanded(
                flex: 1,
                child: TextField(
                  controller: txController,
                ),
              ),
              CustomButton(
                "发送",
                sendOneMessage,
                width: 60,
              ),
              CustomButton(
                "连接设备",
                toConnectDevice,
                width: 80,
                margin: EdgeInsets.only(left: 10, right: 10),
              ),
              CustomButton(
                "断开连接",
                () async {
                  await deviceModel.disconnect();
                  setState(() {
                    revMsgLst.add(TimeUtils.getCurrentTime() + " 断开连接");
                  });
                },
                width: 80,
                margin: EdgeInsets.only(left: 10, right: 10),
              ),
            ],
          ),
          Expanded(
            flex: 1,
            child: ListView.builder(
                itemCount: revMsgLst.length,
                itemBuilder: (BuildContext context, int index) {
                  return CustomText(
                    revMsgLst[index],
                    isEllipsis: false,
                    padding: EdgeInsets.all(10),
                    bgColor: Colors.white,
                    margin: EdgeInsets.only(bottom: 1),
                  );
                }),
          ),
        ],
      ),
    );
  }

  void sendOneMessage() {
    if (bluetoothCharacteristic != null) {
      bluetoothCharacteristic.write([0xA5, 0x5A, 0x04]);
      revMsgLst.add(TimeUtils.getCurrentTime() + " 发送-->A5 5A 04");
      setState(() {
      });
    }
  }

  void sendAllwaysMessage() {}

  Future<void> toConnectDevice() async {
    setState(() {
      revMsgLst.clear();
    });

    await deviceModel.connect();
    setState(() {
      revMsgLst.add(TimeUtils.getCurrentTime() + " 连接完成");
    });

    List<BluetoothService> services = await deviceModel.discoverServices();
    revMsgLst.add(TimeUtils.getCurrentTime() + "发现服务->${services.length}个");
    services.forEach((service) {
      revMsgLst.add(TimeUtils.getCurrentTime() + "发现服务->${service.uuid}");
    });
    setState(() {
    });

    revMsgLst.add(TimeUtils.getCurrentTime() + "监听服务->${services.first.uuid}");
    setState(() {
    });
    var characteristics = services.first.characteristics;
    String data = "";
    for (BluetoothCharacteristic c in characteristics) {
      data += "${await c.read()} ";
    }
    revMsgLst.add(TimeUtils.getCurrentTime() + "data-->$data");
    setState(() {
    });

    bluetoothCharacteristic = characteristics.first;
    bluetoothCharacteristic.setNotifyValue(true);
    bluetoothCharacteristic.value.listen((value) {
      revMsgLst.add(TimeUtils.getCurrentTime() + "接收 value-->$value");
      setState(() {
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    deviceModel.disconnect();
  }
}
